package com.cn.wanxi.consumer.service.impl;

import com.cn.wanxi.consumer.domain.entity.User;
import com.cn.wanxi.consumer.domain.model.ResultModel;
import com.cn.wanxi.consumer.mapper.UserMapper;
import com.cn.wanxi.consumer.service.IUserService;
import com.cn.wanxi.consumer.util.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName UserService
 * @Description 用户服务层
 * @Author JiJiang
 * @Date 2022/9/28 21:35
 * @Version 1.0
 */

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @MethodName saveUser2DB
     * @Description 将用户保存到数据库
     * @Param [user]
     * @Return com.cn.wanxi.consumer.domain.model.ResultModel
     **/
    @Override
    public ResultModel saveUser2DB(User user) {

        int affectedRow = userMapper.insert(user);
        //数据库添加成功后
        if (affectedRow > 0) {
            Long id = user.getId();
            String username = user.getUsername();
            redisTemplate.opsForValue().set(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + username, id);
        }


        return ResultModel.getResult(affectedRow);
    }

    @Override
    public ResultModel loadUsers2Redis() {

        //查询数据库的所有用户
        List<User> userList = userMapper.selectList();

        int userCount = Objects.isNull(userList) ? 0 : userList.size();

        //遍历将数据库用户加入到redis中
//        userList.forEach((item) -> {
////            redisTemplate.opsForValue().set(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + item.getUsername(), item);
//            redisTemplate.opsForValue().set(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + item.getUsername(), item.getId());
//        });


        for (int i = 0; i < userList.size(); i++) {
            redisTemplate.opsForValue().set(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + userList.get(i).getUsername(), userList.get(i).getId());
        }


        return ResultModel.getResult(userCount);
    }


}
